module ui {

    export class MovieClip extends egret.DisplayObjectContainer {

        protected textures: Array<egret.Texture>;

        protected framerate: number = 25;

        protected bitmap: egret.Bitmap;

        protected dt: number = 1000;

        protected passTime: number = 0;

        protected isLoop: boolean = true;

        protected factor: number = -0.5;

        public constructor(textures: Array<egret.Texture>, framerate: number, isLoop: boolean = true, factor: number = -0.5) {
            super();
            this.isLoop = isLoop;
            this.textures = textures;
            this.framerate = framerate;
            this.factor = factor;
            this.bitmap = new egret.Bitmap();
            this.addChild(this.bitmap);
            this.dt = this.dt / this.framerate;
            this.nextFrame();
        }

        private lastTimeStamp: number = 0;

        public stop(): void {
            egret.stopTick(this.onTick, this);
        }

        public onTick(timestamp: number): boolean {
            if (this.lastTimeStamp == 0) {
                this.lastTimeStamp = timestamp;
                return false;
            }

            let dt: number = timestamp - this.lastTimeStamp;
            this.lastTimeStamp = timestamp;
            this.passTime += dt;
            if (this.passTime > this.dt) {
                this.nextFrame();
                this.passTime = 0;
            }
        }

        protected currentIdx: number = 0;

        protected complete: boolean = false;

        private eventData: any;

        public setEventData(eventData: any) {
            this.eventData = eventData;
        }

        protected nextFrame(): void {
            if (this.complete) {
                this.dispatchEvent(new egret.Event(events.MovieEvent.COMPLETE, false, false, this.eventData));
            }
            this.complete = false;

            let texture: egret.Texture = this.textures[this.currentIdx];
            this.bitmap.texture = texture;
            this.reposition(texture);
            this.currentIdx = ++this.currentIdx % this.textures.length;
            if (this.currentIdx == 0) {
                this.complete = true;
                if (!this.isLoop) {
                    manager.TickManager.getInstance().removeTick(this);
                }
            }
        }

        public play(frame: number): void {
            this.currentIdx = frame;
            this.nextFrame();
            egret.startTick(this.onTick, this);
        }


        protected reposition(texture: egret.Texture): void {
            this.bitmap.x = texture.textureWidth * this.factor;
            this.bitmap.y = texture.textureHeight * this.factor;
        }

    }
}